import React from 'react'
import menuRoute from 'routes/menuRoute'

import constants from 'share/constants'
import {messages} from "share/common";
import {Form, message, Table, Button, Modal, DatePicker, Radio, Popover} from 'antd'

const RadioGroup = Radio.Group;

import moment from 'moment'
import SearchArea from 'components/search-area'
import ExportModal from 'components/template/export-modal/export-modal'
import bookingService from 'containers/booking-management/booking-manager.service'
import bookingManagerService from "./booking-manager.service";

class BookingCommissioner extends React.Component {
  constructor(props) {
    super(props);
    this.newSearch = [// 如果是开通了订票平台则搜所条件有如下更多
      {type: 'input', id: 'passengerSize', label: messages('booking-management.key110')/*乘机人数*/},
      {type: 'date', id: 'submitDate', label: messages('common.submit.date')/*提交日期*/},
      {
        type: 'select', id: 'type', label: messages('booking-management.key7')/*类型*/,
        options: [
          {value: 1001, label: messages('booking-management.key93')/*订票*/},
          {value: 1002, label: messages('booking-management.key95')/*改签*/},
          {value: 1003, label: messages('booking-management.key94')/*退票*/},
        ]
      },
    ]
    this.state = {
      isOpenBookingPlatform: false,// 是否开启了订票平台
      loading: false,
      searchForm: [
        {type: 'input', id: 'name', label: messages('common.applicant')/*申请人*/},
        {type: 'input', id: 'businessCode', label: messages('components.key107'/*单号*/)},
      ],
      searchParams: {},
      columns: [
        {
          title: messages('booking-management.key2'/*更新状态*/),
          dataIndex: 'hasHandled',
          render: value => value ? '-' : messages('booking-management.key3'/*有更新*/)
        },
        {title: messages('booking-management.key4'/*申请人*/), dataIndex: 'name'},
        {title: messages('booking-management.key110')/*乘机人数*/, dataIndex: 'passengerSize'},
        {
          title: messages('booking-management.key5'/*提交日期*/),
          dataIndex: 'lastModifiedDate',
          render: value => moment(value).format('YYYY-MM-DD')
        },
        {
          title: messages('components.key107'/*单号*/),
          dataIndex: 'businessCode',
          render:(value) => {
            return (
              <Popover placement="topLeft" content={value}>{value}</Popover>
            )
          }
        },
        {
          title: messages('booking-management.key7'/*类型*/),
          dataIndex: 'type',
          render: value => constants.getTextByValue(value, 'bookerType')
        },//1001订票 1002改签 1003退票
        {title: messages('booking-management.key8'/*已记录*/), dataIndex: 'hasRecorded'}
      ],
      data: [],
      pagination: {
        total: 0
      },
      page: 0,
      pageSize: 10,
      modalVisible: false,
      startDate: null, //导出数据的开始时间
      endDate: null,  //导出数据的结束时间
      dateRadio: 'all', //导出数据选择的时间类型
      applicationOID: '',
    };
    this.bookingDetail = menuRoute.getRouteItem('booking-details', 'key');
  }

  componentWillMount() {
    const {searchForm} = this.state;
    bookingManagerService.travelSuppliers().then(res => {
      if (res.data && res.data['2001']) {
        let isHave = false;
        res.data['2001'].map(item => {
          if (item.supplyId === 10051) {
            isHave = true;
          }
        })
        if(isHave){
          this.setState({
            isOpenBookingPlatform: true,
            searchForm: searchForm.concat(this.newSearch),
          }, () => {
            this.getList();
          })
        }else{
          this.getList();
        }
      }
    }).catch(err => {
      message.log(err.response.data.message);
    })
  }

  getList = () => {
    const {page, pageSize, searchParams, isOpenBookingPlatform} = this.state;
    this.setState({loading: true});
    const paramsOption = {
      page,
      size: pageSize,
      type: null,
      oldFunction: !isOpenBookingPlatform,
    }
    bookingService.getCommissionerList(paramsOption, searchParams).then(res => {
      this.setState({
        loading: false,
        data: res.data,
        pagination: {
          total: Number(res.headers['x-total-count']),
          onChange: this.onChangePager,
          current: page + 1
        }
      })
    })
  };

  onChangePager = (page) => {
    if (page - 1 !== this.state.page) {
      this.setState({page: page - 1}, () => {
        this.getList()
      })
    }
  };

  search = (params) => {
    if (params.submitDate) {
      params.submitDate = moment(params.submitDate).format('YYYY-MM-DD');
    }
    this.setState({
      searchParams: params,
      page: 0,
      pagination: {total: 0}
    }, () => {
      this.getList()
    })
  };

  handleModalShow = () => {
    this.setState({
      modalVisible: true,
      startDate: null,
      endDate: null,
      dateRadio: 'all'
    })
  };

  //设置导出的时间
  setDate = (type, date) => {
    if (type === 'startDate') {
      this.setState({
        startDate: date ? moment(date).format('YYYY-MM-DD 00:00:00') : null,
        dateRadio: (date || this.state.endDate) ? '' : 'all'
      })
    } else if (type === 'endDate') {
      this.setState({
        endDate: date ? moment(date).format('YYYY-MM-DD 23:59:59') : null,
        dateRadio: (date || this.state.startDate) ? '' : 'all'
      })
    } else {
      if (type === 'one' || type === 'three') {
        let year = new Date().getFullYear();
        let month = new Date().getMonth() + 1;
        let startDate = (type === 'one' ? `${year}-${month}-1` : `${year}-${month - 2}-1`);
        startDate = moment(startDate).format('YYYY-MM-DD 00:00:00');
        let endDate = moment(new Date()).format('YYYY-MM-DD 23:59:59');
        this.setState({
          dateRadio: type,
          startDate,
          endDate
        })
      } else {
        this.setState({
          dateRadio: type,
          startDate: null,
          endDate: null
        })
      }
    }
  };

  // //导出数据
  // handleExport = () => {
  //   let startDate = this.state.startDate;
  //   let endDate = this.state.endDate;
  //   let dateRadio = this.state.dateRadio;

  //   bookingService.exportCommissionerData(startDate, endDate).then(res => {
  //     if (res.status === 200) {
  //       let b = new Blob([res.data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
  //       FileSaver.saveAs(b, `${messages('booking-management.key9'/*订票信息*/)}.xlsx`);
  //       message.success(messages('booking-management.key10'/*导出成功*/));
  //     }
  //   }).catch(e => {
  //     let blob = new Blob([e.response.data]);
  //     let reader = new FileReader();
  //     reader.readAsText(blob);
  //     reader.addEventListener("loadend", () => {
  //       let result = reader.result;
  //       if (result && typeof result === 'string') {
  //         result = JSON.parse(result);
  //         if (result.message) {
  //           message.error(`${messages('booking-management.key11'/*导出失败*/)}，${result.message}`)
  //         } else{
  //           message.error(messages('booking-management.key11'/*导出失败*/))
  //         }
  //       }
  //     });
  //     reader.addEventListener('error', () => {
  //       message.error(messages('booking-management.key11'/*导出失败*/))
  //     })
  //   })
  // };

  //查看订票详情
  handleRowClick = (record) => {
    let path = this.bookingDetail.url.replace(":applicationOID", record.applicationOID)
      .replace(":recordOID", record.travelOperationRecordOID)
      .replace(":isNew", this.state.isOpenBookingPlatform);
    this.setState({applicationOID: record.applicationOID});
    this.context.router.push(path);
  };

  render() {
    const {isOpenBookingPlatform, loading, searchForm, pagination, columns, data, modalVisible, startDate, endDate, dateRadio} = this.state;
    return (
      <div className="booking-commissioner">
        <SearchArea
          searchForm={searchForm}
          submitHandle={this.search}
          clearHandle={() => this.search({})}
        />
        <div className="table-header">
          <div className="table-header-buttons">
            <Button
              type="primary"
              onClick={this.handleModalShow}
            >
              {messages('booking-management.key12'/*导出数据*/)}
            </Button>
          </div>
          <div className="table-header-title">
            {messages('common.total', {total: `${pagination.total || 0}`})/*共搜索到 {total} 条数据*/}
          </div>
        </div>
        <Table
          rowKey={(record, index) => index}
          columns={columns}
          dataSource={data}
          pagination={pagination}
          loading={loading}
          onRow={record => ({
            onClick: () => this.handleRowClick(record)
          })}
          bordered
          size="middle"
        />
        <Modal
          title={messages('booking-management.key12'/*导出数据*/)}
          okText={messages('booking-management.key13'/*导出*/)}
          visible={modalVisible}
          onCancel={() => this.setState({modalVisible: false})}
          footer={
            <div>
              <Button
                onClick={() => this.setState({modalVisible: false})}
                style={{float: "right", marginLeft: "16px"}}
              >
                {messages("common.cancel")}
              </Button>
              <ExportModal
                type="btn"
                exportTitle={messages("common.ok")}
                exportType={isOpenBookingPlatform ? "TRAVEL_BOOK_EXPORT_NEW" : "TRAVEL_BOOK_EXPORT"}
                btnType="primary"
                exportCondition={{
                  billCheckSearchCommand: (!startDate && !endDate) ? {} : {
                    beginDate: startDate,
                    endDate
                  }
                }}
                exportCommand={isOpenBookingPlatform ? "TRAVEL_BOOK_EXPORT_NEW" : 'TRAVEL_BOOK_EXPORT'}
              />
            </div>
          }>
          <p>{messages('booking-management.key14'/*请选择最后编辑日期*/)}</p>
          <div>
            <DatePicker
              value={startDate ? moment(startDate) : startDate}
              placeholder={messages('booking-management.key15'/*开始日期*/)}
              onChange={value => this.setDate('startDate', value)}
            />
            &nbsp;&nbsp;至&nbsp;&nbsp;
            <DatePicker
              value={endDate ? moment(endDate) : endDate}
              placeholder={messages('common.end.date')/*结束日期*/}
              onChange={value => this.setDate('endDate', value)}
            />
          </div>
          <div style={{marginTop: 10}}>
            <RadioGroup onChange={e => this.setDate(e.target.value || e.currentTarget.value)} value={dateRadio}>
              <Radio value='all'>{messages('common.all')/*全部*/}</Radio>
              <Radio value='one'>{messages('common.this.month')/*当月*/}</Radio>
              <Radio value='three'>{messages('booking-management.key16'/*近三个月*/)}</Radio>
            </RadioGroup>
          </div>
        </Modal>
      </div>
    )
  }
}

BookingCommissioner.contextTypes = {
  router: React.PropTypes.object
};

const wrappedApproveRequest = Form.create()(BookingCommissioner);

export default wrappedApproveRequest
